package com.dc.controller;

import com.dc.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller
public class MyController {

    @RequestMapping({"/", "/index"})
    public String index(Model model) {
        model.addAttribute("msg", "Hello,SpingBoot Shiro!");
        return "index";
    }


    @RequestMapping("/user/add")
    public String toAdd() {
        return "user/add";
    }


    @RequestMapping("/user/update")
    public String toUpdate() {
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(@RequestParam("username") String name,
                        @RequestParam("password") String password,
                        HttpServletRequest request,
                        Model model) {
        System.out.println("request-->rememberMe==>"+request.getParameter("rememberMe"));
        boolean rememberMe = true;
        if(request.getParameter("rememberMe")==null){
            rememberMe = false;
        }
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(name, password,rememberMe);
        try {
            subject.login(token); //自动化认证 执行登录方法，如果没有异常就说明OK了
            System.out.println("subject.getPrincipal()有东西啦");
            User user = (User) subject.getPrincipal();//认账方法里传入账户数据才能拿到东西
            // 将 账户数据 放到 Session 中
            subject.getSession().setAttribute("user", user);
            model.addAttribute("msg",name);
            return "redirect:/index";
        } catch (UnknownAccountException accountException) {
            // 用户名不存在
            model.addAttribute("msg", "用户名错误");
            return "login";
        } catch (IncorrectCredentialsException e) {
            // 密码错误
            model.addAttribute("msg", "密码错误");
            return "login";
        }
    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String unAuthorizationInfo(){
        return "未授权无法访问此页面";
    }

    /**
     * 注销登录
     */
    @GetMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout(); // 会自动清空 Session
        return "redirect:/index";
    }

    @RequestMapping("/user/admin")
    public String admin(){
        return "user/admin";
    }


}
